


/**
* @file char.c
* @brief 一个简单的字符设备
* @author zshare
* @version v1.0
* @date 2022-02-13
* @history  
*/


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>

#define _log_
#ifdef _log_
	#define log_print(format, arg...) printf(format,## arg)
#else
	#define log_print(format, arg...) do{}while(0)
#endif
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
#define nil NULL
#define FALSE 1
#define TRUE 0
#define CMD_GET_VERSION 0x01
#define pcalloc(x,size,type) do{ if((x = (type *)calloc(1,size)) == NULL){ return FALSE; } }while(0)
#define pfree(ptr) do{ if(ptr != NULL) { free(ptr); } ptr = NULL; }while(0)

int main(){
	u32 len = 0,i = 0;
	u8 *ver = nil;//版本号
	u8 buffer[32] = {0};//存取数据缓存

	//分配一块内容用来存放字符设备版本号
	pcalloc(ver, 16, u8);

	int fd = open("/dev/tchar0", O_RDWR);//以可读可写方式打开
	if(fd < 0){
		log_print("open failed.\n");
		return -1;
	}

	//通过ioctl获取版本
	ioctl(fd, CMD_GET_VERSION, ver);
	printf("版本:%s.\n",ver);
	
	//向文件写入1-32
	for(i = 0;i < 32;i++){ buffer[i] = i+1; }
	write(fd, buffer, 32);//将buffer数据写入字符设备
	memset(buffer, 0, 32);//将buffer清零
	read(fd, buffer, 32);//从内核读出32个数据
	for(i = 0;i < 32;i++){
		if(i != 0 && i % 16 == 0) { printf("\n"); }
		printf("%02d ", buffer[i]);
	}
	printf("\n");
	pfree(ver);
	return 0;
}









